package com.zhengke.controller.gywm;

import com.zhengke.common.BaseController;
import com.zhengke.common.object.AjaxDone;
import com.zhengke.common.util.DateUtil;
import com.zhengke.common.util.FastDfsApiOpr;
import com.zhengke.common.util.LoadProperties;
import com.zhengke.pojo.AboutPhone;
import com.zhengke.service.gywm.GywmService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * *******************************
 * 项目名称：tvmallws
 * 文件名称：GYWMController
 * 类说明：  关于我们
 * 创建时间：2020/1/6 16:55
 *
 * @author 王鑫
 * @version 1.0
 * *******************************
 */
@Controller
@RequestMapping("GYWM")
public class GywmController extends BaseController {

    @Autowired
    private GywmService service;

    /**
     * 跳转到关于我们页面
     *
     * @param map
     * @return
     */
    @RequestMapping("toGywm.do")
    public String toGywm(ModelMap map) throws Exception {
        List<AboutPhone> rtnList = service.queryMsg();
        map.put("list", rtnList);
        return "gywm/gywm001";
    }


    /**
     * 跳转到详情页面
     *
     * @return
     */
    @RequestMapping("toDetails.do")
    public String toDetails(String id, ModelMap model, HttpServletRequest request) {
        try {
            AboutPhone ap = service.selectById(Integer.parseInt(id));
            model.put("ap", ap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "gywm/gywmDetails";
    }

    /**
     * 保存修改
     *
     * @return
     */
    @RequestMapping("toSave.do")
    @ResponseBody
    public AjaxDone toUpData(HttpServletRequest request) {
        String userName = getLoginObject(request).getUserName();
        //System.out.println("userName------》" + userName);

        String id = request.getParameter("id");
        String type = request.getParameter("type");
        String content = request.getParameter("content");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String updateTime = df.format(new Date());// new Date()获取当前系统时间
        AboutPhone ap = new AboutPhone();
        ap.setContent(content);
        ap.setId(Integer.parseInt(id));
        ap.setType(Integer.parseInt(type));
        ap.setUpdateTime(updateTime);
        ap.setUpdateUser(userName);

        try {
            int rst = service.toUpData(ap);
            if (rst == -1) {
                return new AjaxDone("300", "保存失败!");
            }
            if (rst >= 0) {
                return new AjaxDone("200", "保存成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后重试!");
    }

    /**
     * 上传图片
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("uploadImage.do")
    public Object updateImage(@RequestParam(value = "file", required = false) CommonsMultipartFile file,String typeName) {

        try {
            String imageFileName = file.getOriginalFilename();
            //System.out.println(imageFileName);
            if (imageFileName.indexOf(".jpg") == -1
                    && imageFileName.indexOf(".gif") == -1
                    && imageFileName.indexOf(".png") == -1
                    && imageFileName.indexOf(".jpeg") == -1) {
                //return new AjaxDone("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
                return layeditUpload(300, "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片", "", "");
            }

            String extName = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            if (file != null && !file.isEmpty()) {
                String newImgName = DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss");
                String path = LoadProperties.findValue("imgPath") + "/" + newImgName + "." + extName;
                File newFile = new File(path);
                if (!newFile.getParentFile().exists()) {
                    newFile.getParentFile().mkdirs();
                }
                FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
                //String rtnPath = LoadProperties.findValue("viewUrl") + "?path=" + newFile.getPath();
                //上传fastDFS后图片完整地址
                String file_id = FastDfsApiOpr.upload(newFile.getPath(), extName);
                //读取config.properties查找访问路径的ip+端口
                String rtnPath = LoadProperties.findValue("FILE_SERVER_URL") + file_id;
                if (newFile != null) {
                    newFile.delete();
                }
                return layeditUpload(0, "上传成功", rtnPath, typeName);
            } else {
                //return new AjaxDone("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
                return layeditUpload(300, "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片", "", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //return new AjaxDone("300", "上传失败");
        return layeditUpload(300, "上传失败", "", "");
    }

    /**
     * layui文本编辑器上传图片返回消息
     *
     * @param code
     * @param msg
     * @param src
     * @param filename
     * @return
     */
    private Object layeditUpload(int code, String msg, String src, String filename) {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> map2 = new HashMap<String, Object>();
        map.put("code", code);    //0表示上传成功,其他表示失败
        map.put("msg", msg); //提示信息，//一般上传失败后返回
        map2.put("src", src);//图片路径
        map2.put("title", filename);//图片名称  //可选
        map.put("data", map2);
        return map;
    }

}
